﻿//==================================================================
// Copyright (C) 2015 福流网络
// 作 者：江怀玉
// 日 期：2015-04-22
// 描 述：用于简化与文件相关操作
// 版 本：1.00
// 修改历史纪录
// 版 本  修改时间      修改人            修改内容
//==================================================================
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace FL.Common.File
{
    #region =========== 文件操作 ===========
    /// <summary>
    /// 文件操作类
    /// </summary>
    [Serializable]
    public class CFile
    {
        //文件创建锁
        private static readonly object obj_Create_Lock = new object();

        /// <summary>
        /// 创建文件(如果目录不存在则自动创建、路径既可以是绝对路径也可以是相对路径
        /// 返回文件数据流，如果创建失败则返回null、如果文件存在则打开它
        /// </summary>
        /// <param name="fileName">文件名</param>
        /// <returns>文件数据流</returns>
        public static System.IO.FileStream Create(string fileName)
        {
            if (fileName.Trim() == String.Empty)
                return null;
            try
            {
                fileName = GetPhyPath(fileName);
                string _Folder = fileName.Substring(0, fileName.LastIndexOf('\\') + 1);
                string _TmpFolder = _Folder.Substring(0, fileName.IndexOf('\\'));
                //逐层创建文件夹
                while (_TmpFolder != _Folder)
                {
                    _TmpFolder = _Folder.Substring(0, fileName.IndexOf('\\', _TmpFolder.Length) + 1);
                    if (!System.IO.Directory.Exists(_TmpFolder))
                        System.IO.Directory.CreateDirectory(_TmpFolder);
                }
                if (System.IO.File.Exists(fileName))
                    return System.IO.File.Open(fileName, System.IO.FileMode.Open, System.IO.FileAccess.ReadWrite);
                else
                    return System.IO.File.Create(fileName);
            }
            catch (Exception ex)
            {
                return null;
            }
        }

        /// <summary>
        /// 获取文件、文件夹绝对路径
        /// </summary>
        /// <returns>绝对路径</returns>
        public static string GetPhyPath()
        {
            string fileName = AppDomain.CurrentDomain.BaseDirectory;
            return fileName.Substring(0, fileName.Length - 1);
        }

        /// <summary>
        /// 根据相对路径获取文件、文件夹绝对路径
        /// </summary>
        /// <param name="fileName">相对路径</param>   
        /// <returns>绝对路径</returns>
        public static string GetPhyPath(string fileName)
        {
            if (fileName.Trim() == String.Empty)
                return String.Empty;
            fileName = fileName.Replace('/', '\\');             //规范路径写法
            if (fileName.IndexOf(':') != -1)
                return fileName;  //已经是绝对路径了
            if (fileName.Length > 0 && fileName[0] == '\\')
                fileName = fileName.Substring(1);
            return string.Format("{0}{1}", AppDomain.CurrentDomain.BaseDirectory, fileName);
        }

        /// <summary>
        /// 获取文件后缀名(带.)
        /// </summary>
        /// <param name="fileName">文件名</param>
        /// <returns>后缀名</returns>
        public static string GetExtName(string fileName)
        {
            if (fileName.Trim() == String.Empty)
                return String.Empty;
            int index = fileName.LastIndexOf(".");
            if (index == -1)
                return string.Empty;
            return fileName.Substring(index);
        }

        /// <summary>
        /// 删除文件
        /// </summary>
        /// <param name="filePath">文件路径</param>
        /// <returns>删除是否成功</returns>
        public static bool DeleteFile(string filePath)
        {
            if (filePath.Trim() == String.Empty)
                return false;
            try
            {
                filePath = CFile.GetPhyPath(filePath);
                if (System.IO.File.Exists(filePath))
                    System.IO.File.Delete(filePath);
                return true;
            }
            catch (FieldAccessException ex)
            {
                return false;
            }
        }

        /// <summary>
        /// 获取指定目录下的文件
        /// </summary>
        /// <param name="folderPath">文件夹路径</param>
        /// <param name="bIncludeChildFolder">是否包含子目录</param>
        /// <returns>文件数组</returns>
        public static string[] GetFiles(string folderPath, bool bIncludeChildFolder)
        {
            if (folderPath.Trim() == String.Empty)
                return new string[] { };
            Stack<string> _LstFiles = new Stack<string>();
            string _SourceDir = GetPhyPath(folderPath);
            if (!System.IO.Directory.Exists(_SourceDir))
                return new string[] { };
            if (_SourceDir[_SourceDir.Length - 1] != '\\')
                _SourceDir += "\\";
            System.IO.FileInfo[] _FileInfo;
            System.IO.DirectoryInfo _RootDicrctoty = new System.IO.DirectoryInfo(_SourceDir);
            _FileInfo = _RootDicrctoty.GetFiles("*.*", System.IO.SearchOption.AllDirectories);
            for (int i = 0; i < _FileInfo.Length; i++)
            {
                _LstFiles.Push(_FileInfo[i].FullName.Substring(_SourceDir.Length));
            }
            return _LstFiles.ToArray();
        }

        /// <summary>
        /// 判断给定的文件路径是否有效
        /// </summary>
        /// <param name="filePath">指定的文件路径</param>
        /// <param name="extName">文件后缀名(.xml,.ini,.log...)</param>
        /// <returns>true-有效的,false-无效的</returns>
        public static bool FilePathIsValid(string filePath, string extName)
        {
            if (filePath == null)
                return false;
            string _FilePath = filePath.Trim();
            if (_FilePath == String.Empty || _FilePath.IndexOf(':') < 0)
                return false;
            if (_FilePath.LastIndexOf(extName) < 0)
                return false;
            return true;
        }
    }
    #endregion
}
